package com.xnf.ssmweb.service.impl;

import com.xnf.ssmweb.dao.UserInfoMapper;
import com.xnf.ssmweb.domain.Role;
import com.xnf.ssmweb.domain.UserInfo;
import com.xnf.ssmweb.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by chendx on 2021/3/30.
 */
@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public List<UserInfo> queryUserInfos() {
        return userInfoMapper.findAll();
    }

    public UserInfo queryUserById(Long id) {
        return userInfoMapper.findById(id);
    }

    public boolean saveUserInfo(UserInfo userInfo) {
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        return userInfoMapper.save(userInfo) > 0 ? true : false;
    }

    public boolean addRoleToUser(String[] roleIds, Long userId) {
        boolean flag = false;
        for (String roleId : roleIds){
            flag = userInfoMapper.addRoleToUser(userId,Long.parseLong(roleId)) > 0? true :false;
            if (!flag) return flag;
        }
        return flag;
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        try {
            userInfo = userInfoMapper.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User(userInfo.getUsername(),userInfo.getPassword(),
                userInfo.getStatus()==1?true:false,true,true,true,getAuthority(userInfo.getRoles()));
        return user;
    }

    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        ArrayList<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles){
            list.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return list;
    }
}
